//
//  AudioSampleBufferPlayerViewController.swift
//  MyVideo
//
//  Created by han on 2021/4/25.
//

import UIKit
import AVFoundation

class AudioSampleBufferPlayerViewController: UIViewController {
    
    @IBOutlet private weak var rearrangeButton: UIButton!
    @IBOutlet private weak var restoreButton: UIButton!
    @IBOutlet private weak var doneButton: UIButton!
    @IBOutlet private weak var titleLabel: UILabel!
    @IBOutlet private weak var artistLabel: UILabel!
    @IBOutlet private weak var currentTimeLabel: UILabel!
    @IBOutlet private weak var durationLabel: UILabel!
    @IBOutlet private weak var timeSlider: UISlider!
    @IBOutlet private weak var playPauseButton: UIButton!
    @IBOutlet private weak var volumeViewContainer: UIView!
    @IBOutlet private weak var routePickerViewContainer: UIView!
    
    let sampleBufferPlayer = SampleBufferPlayer()
    
    private var playlistViewController: AudioPlaylistViewController {
        
        guard let viewController = children.first as? AudioPlaylistViewController
            else { fatalError("playlistViewController has not been set") }
        
        return viewController
    }
    
    private var currentOffsetObserver: NSObjectProtocol!
    private var currentItemObserver: NSObjectProtocol!
    private var playbackRateObserver: NSObjectProtocol!
    
    
    @IBAction func restorePlaylist() {
//        playlistViewController.restorePlaylist()
        
    }
    
    @IBAction func rearrangePlaylist() {
        
    }
    
    @IBAction func doneWithPlaylist() {
        
    }
    
    @IBAction func previewAction(_ sender: Any) {
        
    }
    
    @IBAction func nextAction(_ sender: Any) {
  
    }
    
    @IBAction func playAction(_ sender: Any) {
        if sampleBufferPlayer.isPlaying {
            sampleBufferPlayer.pause()
        } else {
            sampleBufferPlayer.play()
        }
    }
    
}

extension AudioSampleBufferPlayerViewController {
    func pause() {
        sampleBufferPlayer.pause()
    }
    
    func play() {
        sampleBufferPlayer.play()
    }
     
    func nextTrack() {
        skipToCurrentItem(offsetBy: 1)
    }
    
    func previousTrack() {
        skipToCurrentItem(offsetBy: -1)
    }
    
    func skip(by distance: TimeInterval) {
        guard let offset = sampleBufferPlayer.currentItemEndOffset else { return }
        
        sampleBufferPlayer.seekToOffset(offset + CMTime(seconds: distance, preferredTimescale: 1000))
        updateCurrentPlaybackInfo()
    }
    
    func skip(to offset: TimeInterval) {
        sampleBufferPlayer.seekToOffset(CMTime(seconds: Double(offset), preferredTimescale: 1000))
        updateCurrentPlaybackInfo()
    }
    
    private func skipToCurrentItem(offsetBy offset: Int) {
        
        guard let currentItemIndex = sampleBufferPlayer.currentItemIndex,
            sampleBufferPlayer.containsItem(at: currentItemIndex + offset)
            else { return }
        
        sampleBufferPlayer.seekToItem(at: currentItemIndex + offset)
    }
   
    private func updateCurrentPlaybackInfo() {
        
        NowPlayingCenter.handlePlaybackChange(playing: sampleBufferPlayer.isPlaying,
                                              rate: sampleBufferPlayer.rate,
                                              position: sampleBufferPlayer.currentItemEndOffset?.seconds ?? 0,
                                              duration: sampleBufferPlayer.currentItem?.duration.seconds ?? 0)
    }
}


extension AudioSampleBufferPlayerViewController: RemoteCommandHandler {
    func performRemoteCommand(_ command : RemoteCommand) {
        switch command {
        case .pause:
            pause()
            
        case .play:
            play()
            
        case .nextTrack:
            nextTrack()
            
        case .previousTrack:
            previousTrack()
            
        case .skipForward(let distance):
            skip(by: distance)
            
        case .skipBackward(let distance):
            skip(by: -distance)

        case .changePlaybackPosition(let offset):
            skip(to: offset)
        }
    }
}
